package com.genius.framework.multitenancy.crontask;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 添加定时任务注册类，用来增加、删除定时任务。
 */
@Component
public class CronTaskRegister implements DisposableBean {

    private final Map<String, TaskSchedule> scheduledTasks = new ConcurrentHashMap<>(16);

    @Autowired
    private TaskScheduler taskScheduler;

    private String scheduledTaskKey;

    /**
     * 新增定时任务
     * @param scheduledTask 自定义的定时任务方法
     * @param cronExpression cron表达式
     */
    public String addCronTask(SchedulingRunnable scheduledTask, String cronExpression) {
        scheduledTaskKey = scheduledTask.getBeanName() + "-" + scheduledTask.getMethodName();
        addCronTask(new CronTask(scheduledTask, cronExpression));
        return scheduledTaskKey;
    }

    private void addCronTask(CronTask cronTask) {
        if (cronTask != null) {
            if (this.scheduledTasks.containsKey(scheduledTaskKey)) {
                removeCronTask(scheduledTaskKey);
            }
            this.scheduledTasks.put(scheduledTaskKey, scheduleCronTask(cronTask));
        }
    }

    /**
     * 移除定时任务
     * @param taskKey
     */
    public void removeCronTask(String taskKey) {
        TaskSchedule taskSchedule = this.scheduledTasks.remove(taskKey);
        if (taskSchedule != null)
            taskSchedule.cancel();
    }

    private TaskSchedule scheduleCronTask(CronTask cronTask) {
        TaskSchedule taskSchedule = new TaskSchedule();
        taskSchedule.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return taskSchedule;
    }

    @Override
    public void destroy() {
        for (TaskSchedule task : this.scheduledTasks.values()) {
            task.cancel();
        }
        this.scheduledTasks.clear();
    }
}